package com.av.record.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.av.recorder.audiorecord.AudioRecordUtils;

public class InputAudioRecordView extends VOJSBCBaseView {

    private ImageView cImageView;
    private InputAudioRecordButton recordButton;
    private boolean startRecord=false;
    private AudioRecordUtils audioRecordUtils;
    private OnAudioRecordCallBack audioRecordCallBack;
    private int maxTimer=60;

    public InputAudioRecordView(Context context) {
        super(context);
    }

    public InputAudioRecordView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public InputAudioRecordView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initViews() {
        super.initViews();
        cImageView=getViewById(rootView,"civ_audio_state");
    }

    @Override
    public String getLayoutId() {
        return "layout_input_audio_record";
    }

    private void initAudioUtil(){
        audioRecordUtils=new AudioRecordUtils(getContext(),maxTimer);
        audioRecordUtils.setAudioFinishRecorderListener(audioFinishRecorderListener);
        audioRecordUtils.startReconrd();
    }

    public void changeRecordState(boolean record){
        cImageView.setImageResource(Res.getMipMapID(record?"ic_bci_input_record_audio":"ic_bci_input_audio_cancel"));
    }

    public void setMaxTimer(int maxTimer) {
        this.maxTimer = maxTimer;
    }

    public void startRecord(){
        startRecord=true;
        initAudioUtil();
    }

    public void setAudioRecordCallBack(OnAudioRecordCallBack audioRecordCallBack) {
        this.audioRecordCallBack = audioRecordCallBack;
    }

    public void stopRecord(boolean success){
        if(startRecord){
            audioRecordUtils.finishRecord(success);
        }
    }

    public void recordTimerShort(){
        cImageView.setImageResource(Res.getMipMapID("ic_bci_input_record_time_d"));
    }

    public void setRecordButton(InputAudioRecordButton recordButton) {
        this.recordButton = recordButton;
    }

    private AudioRecordUtils.AudioFinishRecorderListener audioFinishRecorderListener=new AudioRecordUtils.AudioFinishRecorderListener() {
        @Override
        public void onFinished(float v, String s, boolean b) {
            startRecord=false;
            if(b){
                if(audioRecordCallBack!=null) {
                    audioRecordCallBack.onAudioPath(v,s);
                }
                if(recordButton!=null){
                    recordButton.recordOver();
                }
            }
        }
    };

    public interface OnAudioRecordCallBack{
        void onAudioPath(float time,String path);
    }
}
